package com.yikaiye.android.yikaiye.ui.fragment;

import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.NonNull;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.base.BaseFragment;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.FragmentAllOrderBinding;
import com.yikaiye.android.yikaiye.dialog.MyDialog;
import com.yikaiye.android.yikaiye.dialog.MyPopupWindow;
import com.yikaiye.android.yikaiye.dialog.VerifiedDialog;
import com.yikaiye.android.yikaiye.model.CheckComboResponseModel;
import com.yikaiye.android.yikaiye.model.CheckModel;
import com.yikaiye.android.yikaiye.model.ChooseServiceModel;
import com.yikaiye.android.yikaiye.model.CommitOrderModel;
import com.yikaiye.android.yikaiye.model.EventBusModel;
import com.yikaiye.android.yikaiye.model.OrderProductModel;
import com.yikaiye.android.yikaiye.ui.activity.home.ConfirmOrderActivity;
import com.yikaiye.android.yikaiye.ui.activity.home.ProductDetailsActivity;
import com.yikaiye.android.yikaiye.ui.activity.order.FaDaDaActivity;
import com.yikaiye.android.yikaiye.ui.activity.order.LookOrderProgressActivity;
import com.yikaiye.android.yikaiye.ui.adapter.OrderStatusAdapter;
import com.yikaiye.android.yikaiye.ui.fragment.viewmodel.OrderStatusViewModel;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.ToastHelper;
import com.yikaiye.android.yikaiye.utils.UMengUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 订单列表页
 */
public class OrderStatusFragment extends BaseFragment<FragmentAllOrderBinding, OrderStatusViewModel> {
    private List<OrderProductModel> data = new ArrayList<>();
    private OrderStatusAdapter adapter;
    private String status;
    private int page = 1;
    private MyDialog myDialog;
    private OrderProductModel mOrderProductModel;
    private int mPosition;
    private Handler mHandler = new Handler();
    private Runnable runnable;
    private OrderProductModel orderProductModel;

    public static OrderStatusFragment newInstance(String status) {
        Bundle bundle = new Bundle();
        bundle.putString(Constant.STATUS_KEY, status);
        OrderStatusFragment fragment = new OrderStatusFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void lazyLoadData() {
        if (getArguments() != null) {
            status = getArguments().getString(Constant.STATUS_KEY, null);
        }
        initDialog();
        binding.smartRefreshLayout.autoRefresh();
        countdown();
    }

    @Override
    protected OrderStatusViewModel bindModel() {
        return getViewModel(this, OrderStatusViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        adapter = new OrderStatusAdapter(mContext);
        binding.recyclerView.setAdapter(adapter);
        adapter.setEmptyViewEnable(true);
        adapter.setEmptyViewLayout(mContext, R.layout.layout_empty_list);
    }

    private void initDialog() {
        myDialog = new MyDialog(getActivity()) {
            @Override
            public void leftClick() {
                dismissDialog();
            }

            @Override
            public void rightClick() {
                viewModel.cancelOrder(mOrderProductModel.getId());
                dismissDialog();
            }
        };
        myDialog.setText(mContext.getString(R.string.cancel_order), mContext.getString(R.string.confirm_cancel_order), mContext.getString(R.string.think), mContext.getString(R.string.confirm_cancel));
    }

    @Override
    protected void initClick() {
        adapter.setOnBtnStatusListener((model, position, tag) -> {
            // tag:1取消订单、2查看进度、3重新下单
            if (tag == 1) {
                UMengUtil.setCountEventId(Constant.ORDER_CANCEL);
                this.mOrderProductModel = model;
                this.mPosition = position;
                if (null != myDialog) {
                    myDialog.showDialog();
                }
            } else if (tag == 2) {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.ID_KEY, model.getId());
                bundle.putString(Constant.FROM_KEY, Constant.order);
                JumpIntent.jump(getActivity(), LookOrderProgressActivity.class, bundle);
            } else if (tag == 3) {
                // 再次下单逻辑： 重新下单-->检查套餐——>是：确定订单页 否：到产品详情页——>点击立即下单按钮
                showLoadingDialog();
                orderProductModel = model;
                List<CheckComboResponseModel.ServiceAttrModel> items = model.getItems();
                if (items != null) {
                    List<ChooseServiceModel> chooseServiceList = new ArrayList<>();
                    for (CheckComboResponseModel.ServiceAttrModel serviceModel : items) {
                        ChooseServiceModel chooseServiceModel = new ChooseServiceModel();
                        chooseServiceModel.setServiceId(serviceModel.getServiceId());
                        chooseServiceModel.setServiceName(serviceModel.getServiceName());
                        String[] s = serviceModel.getSelectInfo().split("-");
                        List<String> remarks = new ArrayList<>(Arrays.asList(s));
                        chooseServiceModel.setRemarks(remarks);

                        if (serviceModel.getBookPeriod() > 1) {
                            chooseServiceModel.setServiceAttrCycle(String.valueOf(serviceModel.getBookPeriod()));
                        }
                        chooseServiceList.add(chooseServiceModel);
                    }
                    CheckModel checkModel = new CheckModel();
                    checkModel.setProductId(model.getProductId());
                    checkModel.setProductReqs(chooseServiceList);
                    viewModel.checkProduct(checkModel);
                }
            }
        });
        adapter.setOnProtocolListener((model, position, tag) -> {
            // tag:1签署电子协议/1查看电子协议
            if (tag == 1) {
                showLoadingDialog();
                this.mOrderProductModel = model;
                this.mPosition = position;
                viewModel.queryVerifyResult(model.getOrderNo(), model.getCustomerType());
            } else if (tag == 2) {
                showLoadingDialog();
                viewModel.lookView(model.getOrderNo());
            }
        });
        adapter.setOnMoreMenuListener((model, position, view) -> {
            this.mOrderProductModel = model;
            this.mPosition = position;
            MyPopupWindow popupWindow = new MyPopupWindow(mContext) {
                @Override
                public void cancelOrder() {
                    if (null != myDialog) {
                        myDialog.showDialog();
                    }
                }
            };
            popupWindow.showPopupWindow(view);
        });

        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                viewModel.getOrderList(status, page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                viewModel.getOrderList(status, page);
            }
        });
        // 订单列表
        viewModel.orderDataModelMutableLiveData.observe(this, orderDataModel -> {
            if (orderDataModel != null && orderDataModel.getRecords() != null) {
                List<OrderProductModel> records = orderDataModel.getRecords();
                if (page == 1) {
                    data = records;
                    adapter.submitList(records);
                    binding.smartRefreshLayout.finishRefresh();
                } else {
                    data.addAll(records);
                    adapter.addAll(records);
                    binding.smartRefreshLayout.finishLoadMore();
                }
            }
        });
        // 订单列表获取失败
        viewModel.mErrorData.observe(this, s -> {
            binding.smartRefreshLayout.finishRefresh();
            binding.smartRefreshLayout.finishLoadMore();
        });

        // 取消订单成功
        viewModel.orderCancelSuccessMutableLiveData.observe(this, s -> {
            dismissLoadingDialog();
            mOrderProductModel.setStatus(2);
            adapter.notifyItemChanged(mPosition, "update-order-item");
        });

        // 取消订单失败
        viewModel.orderCancelErrorMutableLiveData.observe(this, s -> {
            ToastHelper.show(s);
            dismissLoadingDialog();
        });

        // 检查套餐存在
        viewModel.checkResponseModelMutableLiveData.observe(this, checkComboResponseModel -> {
            dismissLoadingDialog();
            if (null != checkComboResponseModel) {
                CommitOrderModel commitOrderModel = new CommitOrderModel();
                commitOrderModel.setProductId(orderProductModel.getProductId());
                commitOrderModel.setProductName(orderProductModel.getProductName());
                commitOrderModel.setPrice(checkComboResponseModel.getProductPrice());
                // android传2
                commitOrderModel.setPlatform(2);
                // 订单类型：2=预订单
                commitOrderModel.setType(2);
                commitOrderModel.setStatus(0);
                commitOrderModel.setVersion("1");
                commitOrderModel.setSource(0);

                for (CheckComboResponseModel.ServiceAttrModel serviceAttrModel : checkComboResponseModel.getProductServiceAttrLists()) {
                    CommitOrderModel.Item item = new CommitOrderModel.Item();
                    item.setServiceId(serviceAttrModel.getServiceId());
                    item.setSelectInfo(serviceAttrModel.getTerminalName());
                    item.setSelectInfoId(serviceAttrModel.getAttrListId());
                    item.setServiceName(serviceAttrModel.getServiceName());
                    item.setPrice(serviceAttrModel.getServiceAttrPrice());
                    item.setBookPeriod(serviceAttrModel.getServiceAttrCycle());
                    item.setProductAttrListId(serviceAttrModel.getId());

                    item.setServiceType(serviceAttrModel.getServiceType());
                    item.setServiceAttrCycleType(serviceAttrModel.getServiceAttrCycleType());
                    item.setTerminalName(serviceAttrModel.getTerminalName());
                    commitOrderModel.getItems().add(item);
                }
                Bundle bundle = new Bundle();
                bundle.putString(Constant.DES_KEY, orderProductModel.getSlogan());
                bundle.putString(Constant.IMG_KEY, orderProductModel.getAppBanner());
                bundle.putSerializable(Constant.MODEL_KEY, commitOrderModel);
                JumpIntent.jump(getActivity(), ConfirmOrderActivity.class, bundle);
            }
        });

        // 检查套餐不存在或报错
        viewModel.checkErrorMutableLiveData.observe(this, s -> {
            dismissLoadingDialog();
            Bundle bundle = new Bundle();
            bundle.putString(Constant.ID_KEY, orderProductModel.getProductId());
            JumpIntent.jump(getActivity(), ProductDetailsActivity.class, bundle);
        });

        // 查看合同
        viewModel.lookViewFddModelMutableLiveData.observe(this, fddModel -> {
            if (fddModel != null && fddModel.getResult() != null) {
                String url = fddModel.getResult().getUrl();
                Bundle bundle = new Bundle();
                bundle.putString(Constant.URL_KEY, url);
                JumpIntent.jump(getActivity(), FaDaDaActivity.class, bundle);
                dismissLoadingDialog();
            }
        });
        viewModel.lookViewErrorMutableLiveData.observe(this, s -> dismissLoadingDialog());

        // 查询认证结果认证
        viewModel.queryResultFddModelMutableLiveData.observe(this, fddModel -> {
            if (null != fddModel) {
                // 00-处理成功；01-处理中；02-处理失败；03-未开始实名认证；04-人工审核中
                if ("00".equals(fddModel.getRespCode())) {
                    // 签署电子协议--/api/yky/app/fdd/signContract/{orderNo}/sign
                    showLoadingDialog();
                    viewModel.signContract(mOrderProductModel.getOrderNo(), mOrderProductModel.getCustomerType());
                } else if ("02".equals(fddModel.getRespCode())) {
                    // 重新认证--/api/yky/app/fdd/identityVerify/verify/reset
                    initVerifyDialog(mOrderProductModel.getOrderNo(), true, mOrderProductModel.getCustomerType());
                } else if ("04".equals(fddModel.getRespCode())) {
                    ToastHelper.show(mContext.getString(R.string.real_name_review));
                } else {
                    // 实名认证--/api/yky/app/fdd/identityVerify/verify
                    initVerifyDialog(mOrderProductModel.getOrderNo(), false, mOrderProductModel.getCustomerType());
                }
            }
            dismissLoadingDialog();
        });
        viewModel.queryResultErrorMutableLiveData.observe(this, s -> dismissLoadingDialog());

        // 签署电子协议
        viewModel.signFddModelMutableLiveData.observe(this, fddModel -> {
            if (fddModel != null && fddModel.getResult() != null) {
                String url = fddModel.getResult().getUrl();
                Bundle bundle = new Bundle();
                bundle.putString(Constant.URL_KEY, url);
                JumpIntent.jump(getActivity(), FaDaDaActivity.class, bundle);
            }
            dismissLoadingDialog();
        });
        viewModel.signErrorMutableLiveData.observe(this, s -> dismissLoadingDialog());

        // 实名认证/重新实名认证
        viewModel.verifyFddModelMutableLiveData.observe(this, fddModel -> {
            if (fddModel != null && fddModel.getResult() != null) {
                String url = fddModel.getResult().getUrl();
                Bundle bundle = new Bundle();
                bundle.putString(Constant.URL_KEY, url);
                JumpIntent.jump(getActivity(), FaDaDaActivity.class, bundle);
            }
            dismissLoadingDialog();
        });
        viewModel.verifyErrorMutableLiveData.observe(this, s -> dismissLoadingDialog());
    }

    private void initVerifyDialog(String orderNo, boolean isReset, int customerType) {
        VerifiedDialog verifiedDialog = new VerifiedDialog(getActivity()) {
            @Override
            public void verify() {
                showLoadingDialog();
                if (isReset) {
                    viewModel.resetVerify(orderNo, customerType);
                } else {
                    viewModel.realNameVerify(orderNo, customerType);
                }

                dismissDialog();
            }
        };
        verifiedDialog.showDialog();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (Constant.refresh_order.equals(eventBusModel.getMessage()) || Constant.signSuccess.equals(eventBusModel.getMessage())) {
                page = 1;
                viewModel.getOrderList(status, page);
            }
        }
    }

    public void countdown() {
        runnable = () -> {
            for (int i = 0; i < adapter.getItems().size(); i++) {
                OrderProductModel model = adapter.getItems().get(i);
                if (model.getTotalTime() > 0) {
                    model.setTotalTime(model.getTotalTime() - 1000);
                    adapter.getItems().set(i, model); //时间未到的 ，只改变数据，暂不刷新条目
                }
            }
            adapter.notifyItemRangeChanged(0, adapter.getItemCount(), R.id.tv_to_pay); //刷新条目中的指定控件

            mHandler.postDelayed(runnable, 1000);
        };
        mHandler.postDelayed(runnable, 1000);
    }

    /**
     * 销毁资源
     */
    public void destroy() {
        mHandler.removeCallbacks(runnable);
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
